#include <QDebug>
#include <QPainter>
#include <QMouseEvent>
#include "ProfileWidget.h"

ProfileWidget::ProfileWidget(QWidget *parent) :
	QWidget(parent), m_iValueMin(0), m_iValueMax(0), m_iRangeMin(0), m_iRangeMax(0),
	m_ptMouse(-1, -1)
{
	this->setMouseTracking(true);
}

void ProfileWidget::paintEvent(QPaintEvent *event)
{
	Q_UNUSED(event);

	QPainter painter(this);
	QRect rect(this->rect());

	painter.fillRect(rect, Qt::transparent);

	QFontMetrics fm(painter.font());
	QString strRMin(QString::number(m_iRangeMin));
	QString strRMax(QString::number(m_iRangeMax));
	QString strVMin(QString::number(m_iValueMin));
	QString strVMax(QString::number(m_iValueMax));
	QRect rectRMin(fm.boundingRect(strRMin));
	QRect rectRMax(fm.boundingRect(strRMax));
	QRect rectVMin(fm.boundingRect(strVMin));
	QRect rectVMax(fm.boundingRect(strVMax));

	rectRMin.adjust(-1, -1, 1, 1);
	rectRMax.adjust(-1, -1, 1, 1);
	rectVMin.adjust(-1, -1, 1, 1);
	rectVMax.adjust(-1, -1, 1, 1);

	int width(qMax(rectVMin.width(), rectVMax.width()));
	int height(qMax(rectRMin.height(), rectRMax.height()));
	QRect rectGraph(rect.adjusted(width, 2, -2, -height));
	this->drawProfile(painter, rectGraph);
	rectRMin.moveTopLeft(rectGraph.bottomLeft());
	rectRMax.moveTopRight(rectGraph.bottomRight());
	rectVMin.moveBottomRight(rectGraph.bottomLeft());
	rectVMax.moveTopRight(rectGraph.topLeft());
	painter.drawText(rectRMin, strRMin);
	painter.drawText(rectRMax, strRMax);
	painter.drawText(rectVMin, strVMin);
	painter.drawText(rectVMax, strVMax);
	painter.drawRect(rectGraph);
}

void ProfileWidget::mouseMoveEvent(QMouseEvent *event)
{
	m_ptMouse = event->pos();
	this->update();
}

void ProfileWidget::leaveEvent(QEvent *event)
{
	m_ptMouse.setX(-1);
	m_ptMouse.setY(-1);
	this->update();
}

void ProfileWidget::SlotClear()
{
	m_data.clear();
}

void ProfileWidget::SlotProfileData(const QList<int> &listProfile)
{
	m_data = QList<int>(listProfile);
	this->calcMinMax();

	this->update();
}

void ProfileWidget::calcMinMax()
{
	QList<int> tmpList(m_data);

	qSort(tmpList);
	m_iValueMax = tmpList.last();
	m_iValueMin = tmpList.first();
	m_iRangeMax = m_data.count() - 1;
	m_iRangeMin = 0;
}

void ProfileWidget::drawProfile(QPainter &painter, QRectF rect)
{
	if(m_data.count() > 0)
	{
		float fXUnit = 1.f * rect.width() / m_iRangeMax;
		float fYUnit = 1.f * rect.height() / (m_iValueMax - m_iValueMin);
		QPolygonF poly;
		QPointF ptBase(rect.topLeft());

		for (int var = m_iRangeMin; var < m_iRangeMax; ++var)
		{
			poly << QPointF(var * fXUnit + ptBase.x(), rect.height() - (m_data.at(var) - m_iValueMin) * fYUnit + ptBase.y());
		}

		painter.save();
		painter.setPen(QPen(Qt::red, fXUnit));
		painter.drawPolyline(poly);
		painter.restore();
	}

	if(rect.contains(m_ptMouse))
	{
		painter.save();
		painter.setPen(Qt::darkGray);
		painter.drawLine(m_ptMouse.x(), rect.top(), m_ptMouse.x(), rect.bottom());
		painter.drawLine(rect.left(), m_ptMouse.y(), rect.right(), m_ptMouse.y());
		painter.restore();

	}
}
